//
//  YRStatus.swift
//  YR 微博
//
//  Created by cyr on 15/10/15.
//  Copyright © 2015年 cyr. All rights reserved.
//

import UIKit
import SDWebImage

/// 微博模型
class YRStatus: NSObject {
    /// 微博创建时间
    var created_at: String?
    
 /// 微博ID
    var id: Int = 0 
    
 /// 微博信息内容
    var text: String?
    
 /// 微博来源
    var source: String?

 /// 配图数组
    var pic_urls: [[String: AnyObject]]? {
        didSet {
            if pic_urls!.count == 0 {
                return
            }
            
            storedPictureURLs = [NSURL]()
            
            for dict in pic_urls! {
                if let urlString = dict["thumbnail_pic"] as? String {
                    storedPictureURLs?.append(NSURL(string: urlString)!)
                }
            }
        }
    }
    
    /**
    配图的 URL 的数组
    */
    var pictureURLs: [NSURL]? {
        return retweeted_status == nil ? storedPictureURLs : retweeted_status?.storedPictureURLs
    }
    
    
 /// 保存 配图的 URL 的数组
    private var storedPictureURLs: [NSURL]?
    
/// 用户
    var user: YRUser?
    
 /// 显示微博所需的行高
    var rowHeight: CGFloat?
    
 /// 转发微博
    var retweeted_status: YRStatus?
    
    /**
        加载微博数据
    */
    class func loadStatus(since_id: Int, max_id: Int, finished: (dataList: [YRStatus]?,error: NSError?) -> ()) {
        YRNetworkTools.sharedTools.loadStatus (since_id, max_id: max_id){ (result, error) -> () in
            if error != nil {
                finished(dataList: nil, error: error)
                return
            }

            
            if let array = result?["statuses"] as? [[String: AnyObject]] {
                // 便利数组
//                print(result)
                var list = [YRStatus]()
                
                for dict in array {
                    list.append(YRStatus(dict:dict))
                    
                }
                self.cacheWebImage(list, finished: finished)
                finished(dataList: list, error: nil)
                
            
            } else {
                
                finished(dataList: nil, error: error)
            }
          
        }
    }
    

    private class func cacheWebImage(list: [YRStatus],finished: (dataList: [YRStatus]?,error: NSError?) -> ()) {
        
        // 创建调度组
        let group = dispatch_group_create()
        
        var dataLength = 0
        
        for status in list {
            
            guard let urls = status.pictureURLs else {
                continue
            }
            
            // 便利 urls 的数组,缓存图片
            for imageUrl in urls {
                
                // 入组
                dispatch_group_enter(group)
                
                SDWebImageManager.sharedManager().downloadImageWithURL(imageUrl, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (image, _, _, _, _) -> Void in
                    
                    let data = UIImagePNGRepresentation(image)!
                    dataLength += data.length
                    
                    dispatch_group_leave(group)
             
                })
            }
        }
        
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            print("缓存图片大小\(dataLength / 1024)K")
            
            finished(dataList: list, error: nil)
        }
    }
    
    
    /**
    *  构造函数
    */
    init(dict:[String: AnyObject]) {
        super.init()
        
        setValuesForKeysWithDictionary(dict)
    }
    override func setValue(value: AnyObject?, forKey key: String) {
    
        if key == "user" {
            
            if let dict = value as? [String: AnyObject] {
                user = YRUser(dict: dict)
            }
            return
        }
        super.setValue(value, forKey: key)
        
        if key == "retweeted_status" {
            if let dict = value as? [String: AnyObject] {
                retweeted_status = YRStatus(dict: dict)
            }
            return
            
        }
    
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    
    override var description: String {
        let keys = ["created_at","id","text","source","pic_urls"]
        
        return "\(dictionaryWithValuesForKeys(keys))"
    }
}
